<?php

namespace Addons\Wish\Controller;
use Home\Controller\AddonsController;

class WishController extends AddonsController{

    public function lists() {
        $this->assign ( 'add_button', false );
        $this->assign ( 'del_button', true );
        $this->assign ( 'check_all', false );

        $model = $this->getModel ( 'wish' );
        parent::common_lists ( $model );
    }

    public function edit($model = null, $id = 0) {
        is_array ( $model ) || $model = $this->getModel ( $model );
        $templateFile = $this->getAddonTemplate ( $model ['template_edit'] );
        $this->common_edit ( $model, $id, $templateFile );
    }

    public function common_edit($model = null, $id = 0, $templateFile = '') {
        is_array ( $model ) || $model = $this->getModel ( $model );
        $id || $id = I ( 'id' );

        // 获取数据
        $data = M ( get_table_name ( $model ['id'] ) )->find ( $id );
        $data || $this->error ( '数据不存在！' );

        $token = get_token ();
        if (isset ( $data ['token'] ) && $token != $data ['token'] && defined ( 'ADDON_PUBLIC_PATH' )) {
            $this->error ( '非法访问！' );
        }

        if (IS_POST) {
            $Model = D ( parse_name ( get_table_name ( $model ['id'] ), 1 ) );
            // 获取模型的字段信息
            $Model = $this->checkAttr ( $Model, $model ['id'] );
            if ($Model->create () && $Model->save ()) {
                $this->_saveKeyword ( $model, $id );

                $this->success ( '保存' . $model ['title'] . '成功！', U ( 'lists?model=' . $model ['name'], $this->get_param ) );
            } else {
                $this->error ( $Model->getError () );
            }
        } else {
            $fields = get_model_attribute ( $model ['id'] );
            $temp['nickname'] = [
                'name' => 'openid',
                'title' => '申报人',
                'disabled' => 1,
                'function' => 'get_nickname_by_openid',
                "is_show" => "1",
                'status' => 1,
                'type' => 'function'
            ];
            $temp['mobile'] = [
                'name' => 'openid',
                'title' => '申报人手机号',
                'disabled' => 1,
                'function' => 'get_mobile_by_openid',
                "is_show" => "1",
                'status' => 1,
                'type' => 'function'
            ];
            $fields[1] = array_merge($temp, $fields[1]);
            $this->assign ( 'fields', $fields );
            $this->assign ( 'data', $data );
            $this->meta_title = '编辑' . $model ['title'];

            $templateFile || $templateFile = $model ['template_edit'] ? $model ['template_edit'] : '';
            $this->display ( $templateFile );
        }
    }
}
